package Namensdienst;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * 
 * the real name service, listens on a port to get messages,
 *  works mutltithreaded with RequestExecuter
 *
 */
public class StandAlone_NS implements Runnable{
    private String hostName;
    private int port;
	/**
	 * contains the information about the names
	 */
    HashMap<String, NameObject> obj_map;
    ArrayList<Object> resolvList;
    boolean isRuning;
    ServerSocket serv_sock;
    Socket mySock;
    InputStream input_strm;
    BufferedReader in;
    OutputStream out;       
    InputStreamReader in_low;
    
    public static void main(String[] args) {
    	StandAlone_NS ns = null;
    	int port = 0;
    	
    	//with arguments
    	if(args.length == 1){
    		try{
    			port = Integer.parseInt(args[0]);
    		}catch(NumberFormatException e){
    			System.out.println("port is not valid");
    			return;
    		}
    		ns = new StandAlone_NS("localhost", port);
    	}else{
    		//without arguments
    		ns = new StandAlone_NS("localhost", 2000);
    		System.out.println("Default port 2000 will be used");
    	}
    	
		Thread thr = new Thread(ns);
		thr.start();
	}
    
    public StandAlone_NS(String serviceHost, int listenPort) {
            this.hostName = serviceHost;
            this.port = listenPort;
            this.isRuning = true;
            obj_map = new HashMap<String, NameObject>();
    }

	@Override
	public void run() {
		//only accepts tcp connections, the message will be executed in a thread
    	try {
			serv_sock = new ServerSocket(port);
		
			while(isRuning){
	            System.out.println("NS: warte auf daten..");
	            mySock = serv_sock.accept();
	            
	            Thread t = new Thread(new RequestExecuter(mySock, obj_map, hostName, port));
				t.start();
				
			}
            
            serv_sock.close();
    	} catch (IOException e) {
			e.printStackTrace();
		}
		
	}


}
